package com.example.demo;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 基于redis的分布式锁
 */
@Service("jedis")
public class JedisLock implements DistributionLock{

    private static final String LOCK_KEY = "DISTRIBUTION_LOCAK";
    private static final int timeout = 5 * 1000;


    /**
     * 去获取锁
     * @return
     */
    public boolean acquire() {
        RedisTemplate redisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
        Long current = System.currentTimeMillis();
        while(current < System.currentTimeMillis() + timeout){
            Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY, "1", timeout, TimeUnit.MILLISECONDS);
            if(aBoolean){
                return true;
            }
            try {
                Thread.sleep(100);
                current += 100;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        throw new RuntimeException("get distribution lock timeout!!!");
    }

    public void release(){
        RedisTemplate redisTemplate = SpringContextUtil.getBean(StringRedisTemplate.class);
        redisTemplate.delete(LOCK_KEY);
    }

}
